<template>
  <div class="tag-sys-user">
    <el-card>
      <tag-content-header search add refresh setting @toolFun="toolFun" :settingData="columns">
        <template #title>
          <span class="title-text">用户列表</span>
        </template>
        <template #toolsPre v-if="$auth('front:handle:import:user')">
          <el-tooltip effect="dark" content="批量导入" placement="top">
            <el-button type="primary" plain circle @click="importUser">
              <icon-svg name="iconImport"></icon-svg>
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="下载模板" placement="top">
            <el-button type="primary" plain circle @click="downloadTemplate">
              <icon-svg name="iconDownload"></icon-svg>
            </el-button>
          </el-tooltip>
        </template>
      </tag-content-header>
      <tag-table
        ref="table"
        @refresh="getList"
        :data="dataList"
        :loading="loading"
        :columns="columns"
        :params="params"
        :total="totalSize"
        :maxHeight="maxTableHeight"
      >
        <template #operation="{ scope }">
          <div class="operation-button-box">
            <el-tooltip effect="dark" content="切换状态" placement="top" :enterable="false">
              <el-switch
                active-color="#74c4b9"
                v-model="scope.row.userStatus"
                :active-value="0"
                :inactive-value="1"
                @change="toggleStatus(scope)"
              >
              </el-switch>
            </el-tooltip>
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <icon-svg name="iconEdit" class="svg-edit" @click.native="handleEdit('edit', scope.row)"></icon-svg>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <icon-svg name="iconDelete" class="svg-delete" @click.native="handleDelete(scope.row)"></icon-svg>
            </el-tooltip>
            <el-tooltip effect="dark" content="重置用户密码" placement="top" :enterable="false">
              <icon-svg name="iconLock" class="svg-lock" @click.native="resetPwd(scope.row)"></icon-svg>
            </el-tooltip>
          </div>
        </template>
      </tag-table>
    </el-card>

    <el-dialog
      title="密码重置"
      :visible.sync="pwdDialogVisible"
      top="10vh"
      :close-on-click-modal="false"
      :before-close="clearPwdDialog"
      append-to-body
      class="tag-edit-dialog sys-user-dialog"
      width="50%"
      v-dialogMove
    >
      <el-form :model="pwdEditForm" label-width="120px" :rules="pwdEditFormRules" ref="pwdEditForm">
        <h4 class="type-title">
          请设置用户【{{ pwdEditForm.loginUname }}】的新密码，建议使用数字、字母和字符的组合密码，提高密码安全等级。
        </h4>
        <el-row :gutter="20">
          <el-form-item label="输入新密码" prop="newLoginPwd">
            <el-input placeholder="请输入新密码" type="password" v-model="pwdEditForm.newLoginPwd"></el-input>
          </el-form-item>
          <el-form-item label="再次输入新密码" prop="confirmNewLoginPwd">
            <el-input
              placeholder="请再次输入新密码"
              type="password"
              v-model="pwdEditForm.confirmNewLoginPwd"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码强度">
            <el-progress
              :percentage="pasStrength.progress"
              :show-text="false"
              :stroke-width="12"
              :class="'psd-strength' + pasStrength.level"
            ></el-progress>
            <span class="pas-strength">
              安全级别：<span :class="'psd-strength' + pasStrength.level">{{ pasStrength.label }}</span>
            </span>
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clearPwdDialog">取消</el-button>
        <el-button type="primary" @click="submitResetPwd">确定</el-button>
      </span>
    </el-dialog>
    <import-dialog ref="importDialog" @refresh="getList"></import-dialog>
    <user-drawer ref="userDrawer" @refresh="getList"></user-drawer>
  </div>
</template>

<script>
import importDialog from './user-import-item'
import userDrawer from './user-edit-item'
import utils from '@/plugins/utils'
export default {
  components: {
    importDialog,
    userDrawer
  },
  data() {
    return {
      dataList: [],
      loading: false,
      columns: [
        {
          show: true,
          label: '登录名',
          prop: 'loginUname',
          search: true,
          searchKey: '',
          sort: true
        },
        {
          show: true,
          label: '姓名',
          prop: 'cnName',
          search: true,
          searchKey: '',
          sort: true,
          align: 'center'
        },
        {
          show: false,
          label: '昵称',
          prop: 'nname',
          search: true,
          searchKey: '',
          sort: true,
          align: 'center'
        },
        {
          show: false,
          label: '英文名',
          prop: 'enName',
          search: true,
          searchKey: '',
          sort: true,
          align: 'center'
        },
        {
          show: true,
          label: '所属公司',
          prop: 'compNm',
          search: true,
          searchKey: '',
          sort: true,
          align: 'center'
        },
        {
          show: true,
          label: '所属部门',
          prop: 'deptNm',
          search: true,
          searchKey: '',
          sort: true,
          align: 'center'
        },
        {
          show: false,
          label: '工号',
          prop: 'empId',
          search: true,
          searchKey: '',
          sort: true,
          align: 'center'
        },
        {
          show: false,
          label: '职位',
          prop: 'userPost',
          search: true,
          searchKey: '',
          sort: true,
          align: 'center'
        },
        {
          show: false,
          label: '状态',
          prop: 'userStatus',
          width: '120',
          dict: 'auth_user_status',
          search: true,
          searchKey: '',
          sort: true,
          align: 'center'
        },
        {
          show: false,
          label: '手机号',
          prop: 'userMobile',
          width: '120',
          search: true,
          searchKey: '',
          sort: true,
          align: 'center'
        },
        {
          show: false,
          label: '邮箱',
          prop: 'userEmail',
          search: true,
          searchKey: '',
          sort: true,
          align: 'center'
        },
        {
          show: 'fixed',
          label: '操作',
          prop: 'operation',
          align: 'center',
          width: 200
        }
      ],
      params: {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      },
      totalSize: 0,
      pwdDialogVisible: false,
      pwdEditForm: {
        userId: '',
        loginUname: '',
        newLoginPwd: '',
        confirmNewLoginPwd: ''
      },
      pwdEditFormRules: {
        newLoginPwd: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { min: 6, max: 100, message: '密码长度应在 6 到 100 个字符之间', trigger: 'blur' }
        ],
        confirmNewLoginPwd: [{ required: true, message: '确认新密码不能为空', trigger: 'blur' }]
      },
      pasStrength: {
        level: 0,
        progress: 0,
        label: '弱'
      }
    }
  },
  watch: {
    'pwdEditForm.newLoginPwd'(val) {
      let progress = utils.checkStrong(val)
      switch (progress) {
        case 0:
          this.pasStrength.level = 1
          this.pasStrength.progress = 10
          this.pasStrength.label = '很弱'
          break
        case 1:
          this.pasStrength.level = 1
          this.pasStrength.progress = 25
          this.pasStrength.label = '弱'
          break
        case 2:
          this.pasStrength.level = 2
          this.pasStrength.progress = 50
          this.pasStrength.label = '中'
          break
        case 3:
          this.pasStrength.level = 3
          this.pasStrength.progress = 75
          this.pasStrength.label = '强'
          break
        case 4:
          this.pasStrength.level = 4
          this.pasStrength.progress = 100
          this.pasStrength.label = '很强'
          break
      }
    }
  },
  computed: {
    maxTableHeight() {
      // 表格最大高度 =  可视窗口高度 - 顶栏高度50 - 内容容器padding - 页面容器padding和border - 工具栏最小高度 - 描述框高度
      var paddingHeight = 0
      if (this.$route.meta.isTab) {
        paddingHeight = 70
      } else {
        paddingHeight = 30
      }
      var height = this.$store.state.common.documentClientHeight - 50 - paddingHeight - 22 - 40
      return height
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl('auth/authUserMgr/pageList'),
        method: 'get',
        params: this.$ajax.setParams(this.params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (data.data.currentPageNum === this.params.currentPageNum) {
            this.dataList = data.data.records
            this.totalSize = data.data.totalSize
          }
        } else {
          this.$message.error('获取用户列表失败！')
        }
        this.loading = false
      })
    },
    toolFun(operation) {
      switch (operation) {
        case 'search':
          // 搜索动作
          this.$refs['table'].searchToggle()
          break
        case 'add':
          // 新增动作
          this.handleEdit()
          break
        case 'refresh':
          // 刷新动作
          this.getList()
          break
      }
    },
    handleEdit(type = 'add', scope = {}) {
      this.$refs.userDrawer.showDrawer(type, scope)
    },
    resetPwd(row) {
      this.pwdEditForm.userId = row.userId
      this.pwdEditForm.loginUname = row.loginUname
      this.pwdDialogVisible = true
    },
    submitResetPwd() {
      this.$refs['pwdEditForm'].validate(valid => {
        if (valid) {
          if (this.pwdEditForm.newLoginPwd !== this.pwdEditForm.confirmNewLoginPwd) {
            this.$message.error('两次输入的密码不一致，请重新输入')
            return
          }
          this.$ajax({
            url: this.$ajax.setUrl('auth/authUserMgr/pwdByReset'),
            method: 'put',
            data: this.$ajax.setData({
              userId: this.pwdEditForm.userId,
              newLoginPwd: utils.crypto(this.pwdEditForm.newLoginPwd),
              pwdStrong: this.pasStrength.level
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.clearPwdDialog()
              this.getList()
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        }
      })
    },
    toggleStatus(scope) {
      let params = {
        userId: scope.row.userId,
        deptId: scope.row.deptId,
        empId: scope.row.empId,
        cnName: scope.row.cnName,
        enName: scope.row.enName,
        loginUname: scope.row.loginUname,
        nname: scope.row.nname,
        userPost: scope.row.userPost,
        sysUser: scope.row.sysUser,
        userStatus: scope.row.userStatus,
        roleIds: [],
        avatarUrl: scope.row.avatarUrl,
        cmntStr: scope.row.cmntStr
      }
      this.$ajax({
        url: this.$ajax.setUrl('auth/authUserMgr'),
        method: 'put',
        data: this.$ajax.setData(params)
      }).then(({ data }) => {
        let mes = { type: '', message: '' }
        if (data && data.code === '0') {
          mes.type = 'success'
          mes.message = '操作成功'
        } else {
          mes.type = 'error'
          mes.message = data.data || data.msg
        }
        this.getList()
        this.$message({
          message: mes.message,
          type: mes.type,
          duration: 2000
        })
      })
    },
    handleDelete(scope) {
      if (!scope.userId) return
      this.$confirm('确认删除【' + scope.loginUname + '】？')
        .then(() => {
          let messageBox = document.getElementsByClassName('el-message-box__wrapper')
          messageBox[0].focus() // 防止按空格键重复确定
          this.$ajax({
            url: this.$ajax.setUrl('auth/authUserMgr/' + scope.userId),
            method: 'delete',
            params: this.$ajax.setParams()
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.getList()
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        })
        .catch(() => {
          return
        })
    },
    importUser() {
      this.$refs.importDialog.showDrawer()
    },
    downloadTemplate() {
      this.$ajax({
        url: this.$ajax.setUrl('stg/stgStdFile/import/tmpl'),
        method: 'get',
        params: this.$ajax.setParams({
          tmplId: 10
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.$dlFile(data.data.fileId)
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    clearPwdDialog() {
      this.pwdEditForm.userId = ''
      this.pwdEditForm.loginUname = ''
      this.pwdEditForm.newLoginPwd = ''
      this.pwdEditForm.confirmNewLoginPwd = ''
      this.$nextTick(() => {
        this.$refs['pwdEditForm'].clearValidate()
      })
      this.pwdDialogVisible = false
    }
  }
}
</script>

<style lang="scss">
.tag-sys-user {
  .operation-button-box svg {
    width: 20px;
    height: 20px;
    cursor: pointer;
  }
}
.sys-user-dialog {
  .el-progress {
    display: inline-block;
    width: 70%;
  }
  .pas-strength {
    display: inline-block;
    width: 30%;
    text-align: right;
  }
}
</style>
